package com.party.web.biz.order;

import com.party.common.constant.Constant;
import com.party.common.utils.PartyCode;
import com.party.core.exception.BusinessException;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderStatus;
import com.party.core.model.order.OrderTrade;
import com.party.core.model.order.PaymentWay;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderTradeService;
import com.party.pay.model.refund.AliPayRefundInput;
import com.party.pay.model.refund.WechatPayRefundInput;
import com.party.pay.service.pay.PayOrderBizService;
import com.party.pay.service.query.QueryAliBizService;
import com.party.pay.service.query.QueryWechatBizService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class QueryBizService {
    /********************** 支付宝 ***********************/
    // 应用id
    @Value("#{refund_ali['alipay.appid']}")
    private String appId;

    // 应用私钥
    @Value("#{refund_ali['alipay.privatekey']}")
    private String privateKey;

    // 支付宝公钥
    @Value("#{refund_ali['alipay.publickey']}")
    private String publickey;

    // 签名方式
    @Value("#{refund_ali['alipay.sign_type']}")
    private String signType;
    /********************** 支付宝 ***********************/

    /********************** 微信 ***********************/
    /********************* pc *************************/
    // 小程序编号
    @Value("#{pay_wechat_pc['wechat.pc.appId']}")
    private String pc_appId;

    // 小程序商户号
    @Value("#{pay_wechat_pc['wechat.pc.mchId']}")
    private String pc_mchId;

    // 微信接口密钥
    @Value("#{pay_wechat_pc['wechat.pc.apiKey']}")
    private String pc_apiKey;
    /********************* pc *************************/
    /********************** 微信 ***********************/

    @Autowired
    IOrderFormService orderFormService;
    @Autowired
    QueryAliBizService queryAliBizService;
    @Autowired
    QueryWechatBizService queryWechatBizService;
    @Autowired
    private IOrderTradeService orderTradeService;
    @Autowired
    private PayOrderBizService payOrderBizService;

    protected static Logger logger = LoggerFactory.getLogger(QueryBizService.class);

    /**
     * 执行查询
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    public Object orderquery(String orderId) throws Exception {
        if (StringUtils.isEmpty(orderId)) {
            logger.error("订单号不能为空");
            return null;
        }
        OrderForm orderForm = orderFormService.get(orderId);
        if (orderForm.getPaymentWay() == null) {
            return null;
        }
        if (orderForm.getPaymentWay().equals(PaymentWay.ALI_PAY.getCode())) {
            // 支付宝
            AliPayRefundInput input = new AliPayRefundInput();
            input.setGateway("https://openapi.alipay.com/gateway.do");
            input.setMethod("alipay.trade.query");
            input.setAppId(appId);
            input.setPrivateKey(privateKey);
            input.setPublickey(publickey);
            input.setSignType(signType);
            return queryAliBizService.getQueryResponse(input, orderId);
        } else if (orderForm.getPaymentWay().equals(PaymentWay.WECHAT_PAY.getCode())) {
            // 微信
            String appId = "";
            String mchId = "";
            String apiKey = "";
            if (orderForm.getTradeType() == null) {
                return null;
            }
            if (orderForm.getTradeType().equals(Constant.CLIENT_WX_PC)) {
                appId = pc_appId;
                mchId = pc_mchId;
                apiKey = pc_apiKey;
            }

            WechatPayRefundInput input = new WechatPayRefundInput();
            input.setAppId(appId);
            input.setMchId(mchId);
            input.setApiKey(apiKey);
            input.setRefundUrl("https://api.mch.weixin.qq.com/pay/orderquery");
            return queryWechatBizService.getQueryResponse(input, orderId);
        }
        return null;
    }


    /**
     * 检查订单交易状态
     *
     * @param payment   金额
     * @param orderForm 订单
     * @return
     */
    public Boolean checkOrderTradeStatus(Float payment, OrderForm orderForm) {
        boolean flag = false;
        try {
            // 存在支付流水记录，生成新订单
            OrderTrade orderTrade = orderTradeService.findByOrderId(orderForm.getId());
            if (orderTrade != null) {
                flag = true;
            } else {
                Object responseObject = this.orderquery(orderForm.getId());
                flag = payOrderBizService.checkOrderStatus(payment, orderForm.getPaymentWay(), responseObject);
            }
            return flag;
        } catch (Exception e) {
            logger.error("订单查询异常", e);
            return null;
        }
    }

    /**
     * 检查订单交易状态
     *
     * @param orderId 订单id
     * @return
     */
    public boolean checkOrderTradeStatus(String orderId) {
        OrderForm orderForm = orderFormService.get(orderId);
        if (!orderForm.getStatus().equals(OrderStatus.ORDER_STATUS_TO_BE_PAID.getCode())) {
            throw new BusinessException(PartyCode.PAYMENT_STATUS_ERROR, "订单状态异常");
        }
        return true;
    }
}